package com.gengzp.mq.server.service.impl;

import com.gengzp.mq.server.mapper.MqTopicMapper;
import com.gengzp.mq.server.model.topic.entity.MqTopic;
import com.gengzp.mq.server.model.topic.req.MqCreateTopicReq;
import com.gengzp.mq.server.model.topic.req.MqEditTopicReq;
import com.gengzp.mq.server.model.topic.resp.MqListTopicResp;
import com.gengzp.mq.server.service.MqTopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName MqTopicServiceImpl
 * @Description 消息主题topic管理服务层实现
 * @Author gengzp
 * @Date 2025/10/22 21:29
 */
@Service
public class MqTopicServiceImpl implements MqTopicService {

    @Autowired
    private MqTopicMapper mqTopicMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createTopic(MqCreateTopicReq req) {
        if (Objects.nonNull(mqTopicMapper.selectTopicByName(req.getTopic()))) {
            throw new RuntimeException(String.format("主题名: %s 已存在, 无法重复创建", req.getTopic()));
        }

        MqTopic mqTopic = new MqTopic();
        mqTopic.setTopic(req.getTopic());
        mqTopic.setDescription(req.getTopicDescription());
        mqTopic.setCreatedTime(new Date());
        mqTopicMapper.insertTopic(mqTopic);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editTopicDescription(MqEditTopicReq req) {
        MqTopic mqTopic = mqTopicMapper.selectTopicByName(req.getTopic());
        if (Objects.isNull(mqTopic)) {
            throw new RuntimeException(String.format("主题名: %s 不存在, 无法修改", req.getTopic()));
        }

        mqTopic.setDescription(req.getTopicDescription());
        mqTopicMapper.updateTopicDescription(mqTopic);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeTopic(String topic) {
        mqTopicMapper.deleteTopic(topic);
    }

    @Override
    public List<MqListTopicResp> list() {
        List<MqTopic> mqTopics = mqTopicMapper.selectAllTopic();
        if (mqTopics == null || mqTopics.isEmpty()) {
            return Collections.emptyList();
        }

        return mqTopics.stream().map(v -> {
            MqListTopicResp resp = new MqListTopicResp();
            resp.setTopic(v.getTopic());
            resp.setDescription(v.getDescription());
            resp.setCreatedTime(v.getCreatedTime());
            return resp;
        }).collect(Collectors.toList());
    }

}
